﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Pharmacy.Web.UI;
using Pharmacy.Entities;
using Pharmacy.Data;
using Pharmacy.Settings.BusinessLayer;

public partial class Admin_RequiredAdjustment : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        FormUtil.RedirectAfterUpdate(GridView1, "RequiredAdjustment.aspx?page={0}");
        FormUtil.SetPageIndex(GridView1, "page");
        FormUtil.SetDefaultButton((Button)GridViewSearchPanel1.FindControl("cmdSearch"));

        DropDownList cboFieldName = (DropDownList)GridViewSearchPanel1.FindControl("cboFieldName");
        cboFieldName.Items.Remove(new ListItem("Requirement Id", "RequirementId"));

        string strPreparedBy = Request.Cookies["LoginUser"].Value;
        WebUser objUser = DataRepository.WebUserProvider.GetByUserId(strPreparedBy);
        if (objUser.Roles == "Manager" || objUser.Roles == "Admin")
        {
            btnApprove.Visible = true;
            txtApproveRemark.Visible = true;
            tbl.Visible = true;
        }
        else
        {
            btnApprove.Visible = false;
            txtApproveRemark.Visible = false;
            tbl.Visible = false;
        }
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string urlParams = string.Format("AdjustmentId={0}", GridView1.SelectedDataKey.Values[0]);
        Response.Redirect("AdjustmentEdit.aspx?" + urlParams, true);
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "CustomSave")
        {
            string ID = e.CommandArgument.ToString().Trim();
            GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
            SaveRequirement(ID, row);
            GridView1.DataBind();
        }
    }

    protected void btnSaveAll_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            HiddenField hdfRequirementId = (HiddenField)row.FindControl("hdfRequirementId");
            SaveRequirement(hdfRequirementId.Value, row);
            hdfRequirementId.Value = hdfRequirementId.Value;
        }
        GridView1.DataBind();
    }

    protected void SaveRequirement(string ID, GridViewRow row)
    {
        TextBox txtAdjustQuantity = (TextBox)row.FindControl("txtAdjustQuantity");
        TextBox txtRemark = (TextBox)row.FindControl("txtRemark");
        Label txtlblDrugId = (Label)row.FindControl("lblDrugId");

        RequiredAdjustment obj;

        int adjustQuantity = 0;

        Int32.TryParse(txtAdjustQuantity.Text, out adjustQuantity);

        if (adjustQuantity == 0)
            return;

        VList<ViewRequiredAdjustment> lst = DataRepository.ViewRequiredAdjustmentProvider.GetAll();
        ViewRequiredAdjustment objView = lst.Find(item => item.DrugId == txtlblDrugId.Text);

        if (string.IsNullOrEmpty(ID))
        {
            obj = new RequiredAdjustment();
            obj.DrugId = objView.DrugId;
            obj.Quantity = Convert.ToInt32(objView.Quantity);
            obj.AdjustQuantity = adjustQuantity;
            obj.FinalQuantity = obj.Quantity + adjustQuantity;
            obj.Remark = txtRemark.Text;

            if (obj.FinalQuantity < 0)
                return;

            DataRepository.RequiredAdjustmentProvider.Insert(obj);
        }
        else
        {
            obj = DataRepository.RequiredAdjustmentProvider.GetByRequirementId(Convert.ToInt64(ID));
            obj.Quantity = Convert.ToInt32(objView.Quantity);
            obj.AdjustQuantity = adjustQuantity;
            obj.FinalQuantity = obj.Quantity + adjustQuantity;
            obj.Remark = txtRemark.Text;

            if (obj.FinalQuantity < 0)
                return;

            DataRepository.RequiredAdjustmentProvider.Save(obj);
        }
    }

    protected void btnApprove_Click(object sender, EventArgs e)
    {
        TransactionManager objTransactionManager = DataRepository.Provider.CreateTransaction();
        objTransactionManager.BeginTransaction();

        try
        {
            string strPreparedBy = Request.Cookies["LoginUser"].Value;
            decimal dTotalAmountIn = 0;
            decimal dTotalAmountOut = 0;
            string strAdjustmentID = string.Empty;

            TList<PoDetails> lstAddPoDetails = new TList<PoDetails>();
            TList<GrnDetails> lstAddGrnDetails = new TList<GrnDetails>();

            TList<PoDetails> lstPoDetails = new TList<PoDetails>();
            TList<GrnDetails> lstGrnDetails = new TList<GrnDetails>();
            TList<StockOutDetails> lstStockOutDetails = new TList<StockOutDetails>();

            string Perfix = ServiceFacade.SettingsHelper.AjustmentPrefix + DateTime.Now.ToString("yyMMdd");
            int Count = 0;
            TList<Adjustment> objAdjustment = DataRepository.AdjustmentProvider.GetPaged(objTransactionManager, "AdjustmentId like '" + Perfix + "' + '%'", "AdjustmentId desc", 0, 1, out Count);
            if (Count == 0)
                strAdjustmentID = Perfix + "001";
            else
            {
                strAdjustmentID = Perfix + String.Format("{0:000}", int.Parse(objAdjustment[0].AdjustmentId.Substring(objAdjustment[0].AdjustmentId.Length - 3)) + 1);
            }

            Adjustment newObj = new Adjustment();
            newObj.AdjustmentId = strAdjustmentID;
            newObj.AdjustmentDate = DateTime.Now;
            newObj.TotalAmountIn = dTotalAmountIn;
            newObj.TotalAmountOut = dTotalAmountOut;
            newObj.PreparedBy = strPreparedBy;
            newObj.Remark = txtApproveRemark.Text;
            newObj.IsComplete = true;
            newObj.IsApproved = true;
            DataRepository.AdjustmentProvider.Insert(objTransactionManager, newObj);

            TList<RequiredAdjustment> lst = DataRepository.RequiredAdjustmentProvider.GetAll(objTransactionManager);
            foreach (RequiredAdjustment item in lst)
            {
                AdjustmentDetails newDetail = new AdjustmentDetails();
                newDetail.AdjustmentId = strAdjustmentID;
                newDetail.DrugId = item.DrugId;
                newDetail.Quantity = item.Quantity;
                newDetail.AdjustQuantity = item.AdjustQuantity;
                newDetail.FinalQuantity = item.FinalQuantity;
                newDetail.Remark = item.Remark;
                DataRepository.AdjustmentDetailsProvider.Insert(objTransactionManager, newDetail);

                // Get Stock list by DrugId
                TList<Stock> lstStock = DataRepository.StockProvider.GetByDrugId(objTransactionManager, item.DrugId);
                if (lstStock.Count > 0)
                    lstStock.Sort("ExpDate DESC");

                DrugDispo objDrug = DataRepository.DrugDispoProvider.GetByDrugId(item.DrugId);

                if (item.AdjustQuantity > 0)
                {
                    // If Adjust is greater than 0
                    dTotalAmountIn += item.AdjustQuantity;

                    if (lstStock.Count > 0)
                    {
                        // If stock exists
                        Stock objStock = lstStock[0];
                        objStock.Quantity += item.AdjustQuantity;
                        DataRepository.StockProvider.Update(objTransactionManager, objStock);
                    }
                    else
                    {
                        // If stock doesn't exist
                        Stock objStock = new Stock();
                        objStock.DrugId = item.DrugId;
                        objStock.Quantity = item.AdjustQuantity;
                        objStock.UnitPrice = objDrug.SellPrice;
                        DataRepository.StockProvider.Insert(objTransactionManager, objStock);
                    }

                    PoDetails objPoDetails = new PoDetails();
                    objPoDetails.DrugId = item.DrugId;
                    objPoDetails.Quantity = item.AdjustQuantity;
                    objPoDetails.RemainQuantity = 0;
                    objPoDetails.Remark = "Tu dong them phieu yeu cau nhap [dung de dieu chinh] ngay " + DateTime.Now.ToString("dd-MM-yyyy");
                    lstPoDetails.Add(objPoDetails);

                    GrnDetails objGrnDetails = new GrnDetails();
                    objGrnDetails.DrugId = item.DrugId;
                    objGrnDetails.Quantity = item.AdjustQuantity;
                    objGrnDetails.PoQuantity = item.AdjustQuantity;
                    objGrnDetails.UnitPrice = objDrug.SellPrice;
                    objGrnDetails.Remark = "Tu dong them phieu nhan hang [dung de dieu chinh] ngay " + DateTime.Now.ToString("dd-MM-yyyy");
                    lstGrnDetails.Add(objGrnDetails);
                }
                else if (item.AdjustQuantity < 0)
                {
                    dTotalAmountOut -= item.AdjustQuantity;
                    int iLeftQuantity = item.AdjustQuantity;

                    if (lstStock.Count > 0)
                    {
                        foreach (Stock itemStock in lstStock)
                        {
                            iLeftQuantity += itemStock.Quantity;

                            if (iLeftQuantity >= 0)
                            {
                                itemStock.Quantity = iLeftQuantity;
                                DataRepository.StockProvider.Update(objTransactionManager, itemStock);
                                break;
                            }

                            itemStock.Quantity = 0;
                            DataRepository.StockProvider.Update(objTransactionManager, itemStock);
                        }
                    }

                    // If stock doesn't exist or stock's quantity is not enough => Create new APO and AGR
                    if (lstStock.Count == 0 || iLeftQuantity < 0)
                    {
                        Stock objStock = new Stock();
                        objStock.DrugId = item.DrugId;
                        objStock.Quantity = 0 - iLeftQuantity;
                        objStock.UnitPrice = objDrug.SellPrice;
                        DataRepository.StockProvider.Update(objTransactionManager, objStock);

                        PoDetails objPoDetails = new PoDetails();
                        objPoDetails.DrugId = objStock.DrugId;
                        objPoDetails.Quantity = objStock.Quantity;
                        objPoDetails.RemainQuantity = 0;
                        objPoDetails.Remark = "Tu dong them phieu yeu cau nhap [dung de dieu chinh] ngay " + DateTime.Now.ToString("dd-MM-yyyy");
                        lstAddPoDetails.Add(objPoDetails);

                        GrnDetails objGrnDetails = new GrnDetails();
                        objGrnDetails.DrugId = objStock.DrugId;
                        objGrnDetails.Quantity = objStock.Quantity;
                        objGrnDetails.PoQuantity = objStock.Quantity;
                        objGrnDetails.UnitPrice = objStock.UnitPrice;
                        objPoDetails.Remark = "Tu dong them phieu nhan hang [dung de dieu chinh] ngay " + DateTime.Now.ToString("dd-MM-yyyy");
                        lstAddGrnDetails.Add(objGrnDetails);
                    }

                    StockOutDetails objStockOutDetails = new StockOutDetails();
                    objStockOutDetails.DrugId = item.DrugId;
                    objStockOutDetails.Quantity = 0 - item.AdjustQuantity;
                    objStockOutDetails.UnitPrice = objDrug.SellPrice;
                    objStockOutDetails.Remark = "Dieu chinh ngay " + DateTime.Now.ToString("dd-MM-yyyy");
                    lstStockOutDetails.Add(objStockOutDetails);
                }

                DataRepository.RequiredAdjustmentProvider.Delete(objTransactionManager, item);
            }

            newObj.TotalAmountIn = dTotalAmountIn;
            newObj.TotalAmountOut = dTotalAmountOut;
            DataRepository.AdjustmentProvider.Update(objTransactionManager, newObj);

            // Case: Input item
            if (lstPoDetails.Count > 0 && lstGrnDetails.Count > 0)
            {
                string grnId = "INP" + ServiceFacade.SettingsHelper.GRNPrefix + DateTime.Now.ToString("yyMMdd") + "001";
                string poid = "INP" + ServiceFacade.SettingsHelper.POPrefix + DateTime.Now.ToString("yyMMdd") + "001";
                Po po = DataRepository.PoProvider.GetByPoId(objTransactionManager, poid);
                if (po == null)
                {
                    po = new Po();
                    po.PoId = poid;
                    po.PoDate = DateTime.Now;
                    po.RequestBy = strPreparedBy;
                    po.IsComplete = true;
                    po.Remark = "Tu dong tao phieu nhap [dieu chinh] ngay " + DateTime.Now.ToString("dd-MM-yyyy");
                    DataRepository.PoProvider.Insert(objTransactionManager, po);
                }
                //Create or Update GRN

                Grn grn = DataRepository.GrnProvider.GetByGrnId(objTransactionManager, grnId);
                if (grn == null)
                {
                    grn = new Grn();
                    grn.PoId = poid;
                    grn.GrnId = grnId;
                    grn.SupplierId = "S001";
                    grn.GrnDate = DateTime.Now;
                    grn.PreparedBy = strPreparedBy;
                    grn.IsComplete = true;
                    grn.Remark = "Tu dong tao phieu nhan hang [dieu chinh] ngay " + DateTime.Now.ToString("dd-MM-yyyy");
                    DataRepository.GrnProvider.Insert(objTransactionManager, grn);
                }

                foreach (PoDetails itemPoDetails in lstPoDetails)
                {
                    itemPoDetails.PoId = poid;
                    DataRepository.PoDetailsProvider.Insert(objTransactionManager, itemPoDetails);
                }

                foreach (GrnDetails itemGrnDetails in lstGrnDetails)
                {
                    itemGrnDetails.GrnId = grnId;
                    DataRepository.GrnDetailsProvider.Insert(objTransactionManager, itemGrnDetails);
                }

                grn.Amount += dTotalAmountIn;
                DataRepository.GrnProvider.Update(objTransactionManager, grn);
            }

            // Case: Input item
            if (lstStockOutDetails.Count > 0)
            {
                string stockOutId = "OUT" + ServiceFacade.SettingsHelper.EAPrefix + DateTime.Now.ToString("yyMMdd") + "001";
                //Create or Update StockOut
                StockOut objStockOut = DataRepository.StockOutProvider.GetByStockOutId(objTransactionManager, stockOutId);
                if (objStockOut == null)
                {
                    objStockOut = new StockOut();
                    objStockOut.StockOutId = stockOutId;
                    objStockOut.StockOutDate = DateTime.Now;
                    objStockOut.TotalAmount = 0;
                    objStockOut.PreparedBy = strPreparedBy;
                    objStockOut.IsComplete = true;
                    objStockOut.Remark = "Tu dong xuat dieu chinh ngay " + DateTime.Now.ToString("dd-MM-yyyy");
                    DataRepository.StockOutProvider.Insert(objTransactionManager, objStockOut);
                }

                foreach (StockOutDetails itemStockOut in lstStockOutDetails)
                {
                    itemStockOut.StockOutId = stockOutId;
                    DataRepository.StockOutDetailsProvider.Insert(objTransactionManager, itemStockOut);
                }

                objStockOut.TotalAmount += dTotalAmountOut;
                DataRepository.StockOutProvider.Save(objTransactionManager, objStockOut);
            }

            // Case: Don't enough item for StockOut => Addition
            if (lstAddPoDetails.Count > 0 && lstAddGrnDetails.Count > 0)
            {
                string grnId = "ADD" + ServiceFacade.SettingsHelper.GRNPrefix + DateTime.Now.ToString("yyMMdd") + "001";
                string poid = "ADD" + ServiceFacade.SettingsHelper.POPrefix + DateTime.Now.ToString("yyMMdd") + "001";
                Po po = DataRepository.PoProvider.GetByPoId(objTransactionManager, poid);
                if (po == null)
                {
                    po = new Po();
                    po.PoId = poid;
                    po.PoDate = DateTime.Now;
                    po.RequestBy = strPreparedBy;
                    po.IsComplete = true;
                    po.Remark = "Tu dong tao phieu nhap them [dieu chinh] ngay " + DateTime.Now.ToString("dd-MM-yyyy");
                    DataRepository.PoProvider.Insert(objTransactionManager, po);
                }
                //Create or Update GRN

                Grn grn = DataRepository.GrnProvider.GetByGrnId(objTransactionManager, grnId);
                if (grn == null)
                {
                    grn = new Grn();
                    grn.PoId = poid;
                    grn.GrnId = grnId;
                    grn.SupplierId = "S001";
                    grn.GrnDate = DateTime.Now;
                    grn.PreparedBy = strPreparedBy;
                    grn.IsComplete = true;
                    grn.Remark = "Tu dong tao phieu nhan hang them [dieu chinh] ngay " + DateTime.Now.ToString("dd-MM-yyyy");
                    DataRepository.GrnProvider.Insert(objTransactionManager, grn);
                }

                foreach (PoDetails itemPoDetails in lstAddPoDetails)
                {
                    itemPoDetails.PoId = poid;
                    DataRepository.PoDetailsProvider.Insert(objTransactionManager, itemPoDetails);
                }

                foreach (GrnDetails itemGrnDetails in lstAddGrnDetails)
                {
                    itemGrnDetails.GrnId = grnId;
                    grn.Amount += itemGrnDetails.Quantity;
                    DataRepository.GrnDetailsProvider.Insert(objTransactionManager, itemGrnDetails);
                }
                DataRepository.GrnProvider.Update(objTransactionManager, grn);
            }

            objTransactionManager.Commit();
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            objTransactionManager.Rollback();
            return;
        }
    }
}
